<route lang="json5" type="page">
{
    layout: "default",
    style: {
        navigationBarTitleText: "购票",
    },
}
</route>

<template>
    <view class="m-base-box m-buy">
        <view class="py-4 px-4">
            <wd-text :text="spotInfo?.spotName" size="20px" bold color="#000"></wd-text>
            <wd-text :text="ticketInfo?.price" mode="price" bold color="#E54D42" prefix="￥" />
        </view>
        <wd-form ref="userForm" :model="subForm">
            <view>
                <wd-card title="选择日期">
                    <view class="pb-4">
                        <wd-calendar
                            v-model="subForm.reservationTime"
                            @confirm="handleConfirm"
                            placeholder="请选择时间"
                            prop="reservationTime"
                            :min-date="minDate"
                            :rules="[{ required: false, message: '请选择时间' }]"
                        />
                        <view class="flex justify-between items-center">
                            <wd-text text="选择数量" size="16px" bold color="#000"></wd-text>
                            <wd-input-number v-model="subForm.ticketCount" @change="handleNumChange" />
                        </view>
                    </view>
                </wd-card>
            </view>
            <view class="mt-2">
                <wd-card title="游客信息">
                    <view class="pb-4 flex flex-col justify-center gap-2">
                        <view
                            v-for="(item, index) in subForm?.userTickInfos || []"
                            :key="index"
                            class="flex flex-col justify-between items-center gap-2"
                        >
                            <wd-input
                                :label="'游客' + (index + 1)"
                                label-width="60px"
                                :prop="'userTickInfos.' + index + '.userName'"
                                clearable
                                v-model="item.userName"
                                placeholder="请输入姓名"
                                :rules="[{ required: true, message: '请输入姓名' }]"
                            />
                            <wd-input
                                label="电话"
                                label-width="60px"
                                :prop="'userTickInfos.' + index + '.userPhone'"
                                clearable
                                v-model="item.userPhone"
                                placeholder="请输入电话"
                                :rules="[
                                    { required: true, message: '请输入电话' },
                                    { required: true, pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' },
                                ]"
                            />
                            <!-- <wd-input
                                label="身份证号"
                                label-width="80px"
                                :prop="'userTickInfos.' + index + '.userIdCard'"
                                clearable
                                v-model="item.userIdCard"
                                placeholder="请输入身份证号"
                                :rules="[
                                    { required: true, message: '请输入身份证号' },
                                    {
                                        required: true,
                                        pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                                        message: '请输入有效的身份证号',
                                    },
                                ]"
                            /> -->
                        </view>
                        <wd-button size="small" type="info" plain @click="addUser">添加</wd-button>
                    </view>
                </wd-card>
            </view>
            <view class="footer flex justify-between items-center">
                <wd-text
                    :text="allPrice"
                    mode="price"
                    bold
                    color="#E54D42"
                    prefix="总价约￥"
                    custom-class="u-self-all"
                />
                <wd-button type="primary" size="large" @click="handleSubmit" block>提交订单</wd-button>
            </view>
        </wd-form>
    </view>
</template>

<script lang="ts" setup>
// import { CNY } from "@dinero.js/currencies";
// import { dinero, add, multiply } from "dinero.js";
import { useToast } from "wot-design-uni";
import { timeFormat } from "@/utils";
import { addUsingPost1, detailUsingGet4, createOrderUsingPost, queryOrderStatusUsingGet } from "@/service/app";
const toast = useToast();
const allPrice = ref(0);
const spotInfo = ref<any>({});
const ticketInfo = ref<any>({});
interface UserItem {
    userName: string;
    userPhone: string;
    userIdCard: string;
}
interface payForm {
    /** 邀请人用户id */
    invitationUserId?: string;
    userId?: string;
    /** 订单ID */
    id?: string;
    /** 预约时间 */
    reservationTime?: any;
    /** 支付方式网页/手机端 */
    payMode?: string;
    /** 金额 */
    price?: number;
    /** 门票id */
    ticketId?: string;
    /** 门票数量 */
    ticketCount?: number;
    /** 与游客门票表关联 */
    userTickInfos?: UserItem[];
    /** 订单状态：已支付/待完成/已完成/未评价 */
    status?: string;
    /** 景区名称 */
    spotName?: string;
    /** 门票名称 */
    ticketName?: string;
}
const minDate = ref(new Date().getTime());
const userForm = ref(null);
const subForm = ref<payForm>({
    reservationTime: "",
    ticketCount: 1,
    userTickInfos: [{ userName: "", userPhone: "", userIdCard: "" }],
});
function handleNumChange(value: any) {
    const price = ticketInfo.value.price;
    const total = price * value.value;
    // 使用 toFixed 方法保留两位小数
    allPrice.value = Number(total.toFixed(2));
}
function addUser() {
    subForm.value.userTickInfos.push({ userName: "", userPhone: "", userIdCard: "" });
}
function handleConfirm(value: any) {
    subForm.value.reservationTime = timeFormat(value.value);
}
function getTicketInfo() {
    detailUsingGet4({ params: { id: spotInfo.value.ticketId } }).then((res) => {
        ticketInfo.value = res?.data || {};
        allPrice.value = res?.data?.price || 0;
        subForm.value.price = res?.data?.price || 0;
        if (ticketInfo.value?.bookTime == "tomorrow") minDate.value = new Date().getTime() + 24 * 60 * 60 * 1000;
    });
}
function handleSubmit() {
    userForm.value
        .validate()
        .then(({ valid, errors }) => {
            if (valid) {
                toast.loading({
                    loadingType: "ring",
                    msg: "提交信息...",
                });
                addUsingPost1({ body: subForm.value }).then((res) => {
                    console.log(res, "addUsingPost1");
                    createOrder(res?.data?.orderId);
                });
            }
        })
        .catch((error) => {
            console.log(error, "error");
        });
}
function createOrder(orderId) {
    toast.loading({
        loadingType: "ring",
        msg: "创建订单...",
    });
    createOrderUsingPost({ body: { id: orderId } }).then((res: any) => {
        console.log(res);
        toast.loading({
            loadingType: "ring",
            msg: "微信支付...",
        });
        wx.requestPayment({
            ...res?.data?.payInfo,
            success(res) {
                console.log(res);
                toast.loading({
                    loadingType: "ring",
                    msg: "支付结果验证中...",
                });
                queryOrderStatusUsingGet({ params: { orderId: orderId } }).then((res: any) => {
                    console.log(res, "支付结果");
                    toast.close();
                    if (res?.data?.wxPayStatus === "SUCCESS") {
                        toast.success(res?.data?.tradeStateDesc);
                        uni.switchTab({ url: "/pages/user/index" });
                    } else {
                        toast.warning(res?.data?.tradeStateDesc);
                    }
                });
            },
            fail(res) {
                console.log(res, "fail");
                toast.close();
                if (res.errMsg === "requestPayment:fail cancel") {
                    toast.error("用户支付取消");
                }
            },
        });
    });
}
onLoad((value) => {
    subForm.value.ticketId = value?.ticketId;
    subForm.value.spotName = value?.spotName;
    subForm.value.ticketName = value?.ticketName;
    spotInfo.value = value;
    getTicketInfo();
});
</script>
<style lang="scss">
.u-self-all {
    font-size: 24rpx;
    text {
        font-size: 32rpx;
    }
}
</style>
<style lang="scss" scoped>
.m-buy {
    padding: 14rpx 0 170rpx 0;
    .footer {
        position: fixed;
        bottom: 0;
        z-index: 9;
        box-sizing: border-box;
        width: 100vw;
        height: 160rpx;
        padding: 20rpx 20rpx 42rpx 20rpx;
        background: #fff;
        border-top-left-radius: 15rpx;
        border-top-right-radius: 15rpx;
    }
}
</style>
